<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="微信号" prop="wechatId">
        <el-input
          v-model="queryParams.wechatId"
          placeholder="请输入微信号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-top: 30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checksystem:service:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['checksystem:service:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checksystem:service:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['checksystem:service:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="el-table-wrapper">
      <el-table v-loading="loading" :data="serviceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" />
        <el-table-column label="微信号" align="center" prop="wechatId" />
        <el-table-column label="二维码图片" align="center" prop="qrcodeUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.qrcodeUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="说明区域内容" align="center" prop="description">
          <template #default="scope">
            <pre style="text-align: left; white-space: pre-wrap; word-wrap: break-word; margin: 0;">{{ scope.row.description }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="是否删除" align="center" prop="isDeleted">
          <template #default="scope">
            <dict-tag :options="dict.sys_yes_no" :value="scope.row.isDeleted"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checksystem:service:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checksystem:service:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="pagination-container"
    />

    <!-- 添加或修改客户服务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="serviceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="微信号" prop="wechatId">
          <el-input v-model="form.wechatId" placeholder="请输入微信号" />
        </el-form-item>
        <el-form-item label="二维码图片URL" prop="qrcodeUrl">
          <image-upload v-model="form.qrcodeUrl" :custom-upload-url="'/common/service/upload'" />
        </el-form-item>
        <el-form-item label="说明区域内容" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" :rows="6" style="width: 100%; min-height: 120px;" />
        </el-form-item>
        <el-form-item label="是否删除" prop="isDeleted">
          <el-select v-model="form.isDeleted" placeholder="请选择">
            <el-option :label="'否'" :value="'N'"></el-option>
            <el-option :label="'是'" :value="'Y'"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Service">
import { listService, getService, delService, addService, updateService } from "@/api/checksystem/service";
import { ElMessage } from 'element-plus'
import { formatDate } from '@/utils/format'
import { useDict } from '@/utils/dict'

const { proxy } = getCurrentInstance();
const { sys_yes_no } = useDict("sys_yes_no");
const dict = reactive({
  sys_yes_no
});

const serviceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    wechatId: null,
    qrcodeUrl: null,
    description: null,
    createTime: null,
    updateTime: null,
    isDeleted: null
  },
  rules: {
    wechatId: [
      { required: true, message: "微信号不能为空", trigger: "blur" },
      { pattern: /^[a-zA-Z][a-zA-Z\d_-]{5,19}$/, message: "微信号格式不正确", trigger: "blur" }
    ],
    qrcodeUrl: [
      { required: true, message: "二维码图片URL不能为空", trigger: "blur" },
      { validator: (rule, value, callback) => {
          if (value && !value.match(/\.(jpeg|jpg|gif|png)$/i)) {
            callback(new Error('请上传JPEG/JPG/GIF/PNG格式的图片'));
            return;
          }
          callback();
        }, trigger: "blur" }
    ],
    description: [
      { required: true, message: "说明区域内容不能为空", trigger: "blur" }
    ],
    isDeleted: [
      { required: true, message: "是否删除不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询客户服务列表 */
function getList() {
  loading.value = true;
  listService(queryParams.value).then(response => {
    // 处理数据，确保isDeleted是字符串格式
    if (response.rows && response.rows.length > 0) {
      response.rows.forEach(row => {
        if (row.isDeleted !== null && row.isDeleted !== undefined) {
          row.isDeleted = String(row.isDeleted) === '1' ? 'Y' : 'N';
        }
      });
    }
    serviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    wechatId: null,
    qrcodeUrl: null,
    description: null,
    createTime: null,
    updateTime: null,
    isDeleted: 'N' // 默认为未删除
  };
  proxy.resetForm("serviceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加客户服务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  getService(id).then(response => {
    // 将表单中的isDeleted转为字符串格式
    if (response.data.isDeleted !== null && response.data.isDeleted !== undefined) {
      response.data.isDeleted = String(response.data.isDeleted) === '1' ? 'Y' : 'N';
    }
    form.value = response.data;
    open.value = true;
    title.value = "修改客户服务";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["serviceRef"].validate(valid => {
    if (valid) {
      // 转换isDeleted为后端需要的格式
      const submitData = { ...form.value };
      if (submitData.isDeleted === 'Y') {
        submitData.isDeleted = 1;
      } else if (submitData.isDeleted === 'N') {
        submitData.isDeleted = 0;
      }
      
      if (form.value.id != null) {
        updateService(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addService(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除客户服务编号为"' + _ids + '"的数据项？').then(function() {
    return delService(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('checksystem/service/export', {
    ...queryParams.value
  }, `service_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style>
.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: center;
}

/* 表单样式 */
.el-form--inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

.el-form--inline .el-form-item {
  margin: 0;
  display: flex;
  align-items: center;
}

.el-form-item__label {
  white-space: nowrap;
  min-width: 120px;
  line-height: 32px;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}

.el-input__wrapper,
.el-date-editor {
  width: 200px;
  height: 32px;
}

/* 分页样式 */
.pagination-container {
  position: fixed;
  bottom: 0;
  left: 200px;
  right: 0;
  background-color: #fff;
  padding: 15px 20px;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid #dcdfe6;
}

/* 表格容器样式 */
.el-table-wrapper {
  margin-bottom: 80px;
}
</style>
